package com.xingfudazi.web.controller.app;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.xingfudazi.app.domain.AppAccount;
import com.xingfudazi.app.domain.AppMember;
import com.xingfudazi.app.domain.AppMemberInfo;
import com.xingfudazi.app.service.IAppAccountService;
import com.xingfudazi.app.service.IAppMemberInfoService;
import com.xingfudazi.app.service.IAppMemberService;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.app.vo.AppMatchMemberVO;
import com.xingfudazi.common.annotation.Log;
import com.xingfudazi.common.core.controller.BaseController;
import com.xingfudazi.common.core.domain.AjaxResult;
import com.xingfudazi.common.core.domain.Result;
import com.xingfudazi.common.core.page.TableDataInfo;
import com.xingfudazi.common.enums.BusinessType;
import com.xingfudazi.common.utils.SecurityUtils;
import com.xingfudazi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.web.bind.annotation.*;

/**
 * 会员-个人信息Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@RestController
@RequestMapping("/app/member-info")
public class AppMemberInfoController extends BaseController {
    @Autowired
    private IAppMemberInfoService appMemberInfoService;

    @Autowired
    private IAppMemberService appMemberService;

    @Autowired
    private IAppAccountService appAccountService;

    @Autowired
    private WxRequestService wxRequestService;

    /**
     * 查询会员-个人信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppMemberInfo appMemberInfo) {
        startPage();
        List<AppMemberInfo> list = appMemberInfoService.selectAppMemberInfoList(appMemberInfo);
        return getDataTable(list);
    }

    /**
     * 导出会员-个人信息列表
     */
    @Log(title = "会员-个人信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppMemberInfo appMemberInfo) {
        List<AppMemberInfo> list = appMemberInfoService.selectAppMemberInfoList(appMemberInfo);
        ExcelUtil<AppMemberInfo> util = new ExcelUtil<AppMemberInfo>(AppMemberInfo.class);
        util.exportExcel(response, list, "会员-个人信息数据");
    }

    /**
     * 获取会员-个人信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appMemberInfoService.selectAppMemberInfoById(id));
    }

    /**
     * 获取会员-个人信息详细信息
     */
    @GetMapping(value = "tk")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        return success(appMemberInfoService.selectAppMemberInfoById(userId));
    }


    private boolean checkRisk(Map<String, ?> response, String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }

        Integer errorCode = (Integer) response.get("errcode");
        if (errorCode == null || errorCode != 0) {
            // Handle error code not being 0 or missing
            return true; // Assuming an error is considered a risk
        }

        @SuppressWarnings("unchecked")
        List<Map<String, ?>> detail = (List<Map<String, ?>>) response.get("detail");

        if (detail == null || detail.isEmpty()) {
            // No details provided, consider as no risk
            return false;
        }

        return detail.stream()
                .filter(item -> "content_model".equals(item.get("strategy")))
                .anyMatch(item -> {
                    Object labelObj = item.get("label");
                    return labelObj instanceof Integer && ((Integer) labelObj) != 100;
                });
    }

    /**
     * 新增会员-个人信息
     */
    @Log(title = "会员-个人信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppMemberInfo appMemberInfo) {
        return toAjax(appMemberInfoService.insertAppMemberInfo(appMemberInfo));
    }

    /**
     * 修改会员-个人信息
     */
    @Log(title = "会员-个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppMemberInfo appMemberInfo) {
        AppMember appMember = appMemberService.getById(appMemberInfo.getNid());
        Long aid = appMember.getAid();
        AppAccount appAccount = appAccountService.selectAppAccountById(aid);
        String openId = appAccount.getWxOpenId();
// 使用该方法来检查 nickname 的风险检测
        Map<String, ?> resNickName = (Map<String, ?>) wxRequestService.riskText(appMemberInfo.getNickName(), openId);
        if (checkRisk(resNickName, appMemberInfo.getNickName())) {
            AjaxResult err = AjaxResult.error("当前用户名 内容存在风险");
            return err;
        }

// 使用该方法来检查 introduce 的风险检测
        Map<String, ?> resIntroduce = (Map<String, ?>) wxRequestService.riskText(appMemberInfo.getIntroduce(), openId);
        if (checkRisk(resIntroduce, appMemberInfo.getIntroduce())) {
            AjaxResult err2 = AjaxResult.error("当前内容 内容存在风险");
            return err2;
        }

// 使用该方法来检查 need 的风险检测
        Map<String, ?> resNeed = (Map<String, ?>) wxRequestService.riskText(appMemberInfo.getNeed(), openId);
        if (checkRisk(resNeed, appMemberInfo.getNeed())) {
            AjaxResult err3 = AjaxResult.error("需求内容 存在风险");
            return err3;
        }

// 使用该方法来检查 email 的风险检测
        Map<String, ?> resEmail = (Map<String, ?>) wxRequestService.riskText(appMemberInfo.getEmail(), openId);
        if (checkRisk(resEmail, appMemberInfo.getEmail())) {
            AjaxResult err4 = AjaxResult.error("邮件内容 存在风险");
            return err4;
        }
        return toAjax(appMemberInfoService.updateAppMemberInfo(appMemberInfo));
    }

    /**
     * 查询动态列表
     */
    @GetMapping("/turn")
    public Result<List<AppMemberInfo>> turn(@RequestParam(defaultValue = "20") Integer pageSize,
                                            Long lastId, String search, String type) {
        return Result.success(this.appMemberInfoService.turn(pageSize,lastId,search,type));

    }

    /**
     * 雷达匹配
     */
    @GetMapping("match-radar")
    public Result<List<AppMatchMemberVO>> getMatch(String four) {

        return Result.success(this.appMemberInfoService.match(four));
    }

}
